package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
)

func main() {
	src := "1.jpg"                 //源文件的相对路径
	dest := "./serverr/1-copy.jpg" //目标文件
	temp := "temp.txt"             //记录累计传输多少字节的中转文件

	srcfile, srcerr := os.OpenFile(src, os.O_RDONLY, os.ModePerm)
	destfile, _ := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE, os.ModePerm)
	temptxt, _ := os.OpenFile(temp, os.O_RDWR|os.O_CREATE, os.ModePerm)

	defer destfile.Close()
	defer srcfile.Close()

	bytes := make([]byte, 10)      //用于传输源文件和目标文件之间的字节数组
	tempbytes := make([]byte, 100) //用于读取或者写入中转文件的字节数组
	var sum int64 = 0              //累计字节

	temptxt.Seek(0, io.SeekStart)

	n, _ := temptxt.Read(tempbytes)
	if srcerr != nil {
		fmt.Println("源文件不存在")
		return
	}
	seekint, _ := strconv.ParseInt(string(tempbytes[:n]), 10, 64)
	fmt.Println(seekint)
	if seekint == 0 {
		fmt.Println("中转文件不存在从头开始拷贝")

		for {
			currentreadlen, eioerr := srcfile.Read(bytes)

			if eioerr != nil || currentreadlen == 0 {
				fmt.Println("文件读取完毕")
				temptxt.Close()
				os.Remove(temp)
				return
			}
			destfile.Write(bytes)
			sum += int64(currentreadlen)
			temptxt.WriteString(strconv.Itoa(int(sum)))
			temptxt.Seek(0, io.SeekStart)

			if sum > 2000 {
				fmt.Println("断电了")

				temptxt.Close()
				return
			}
		}
	} else {
		//断点续传

		fmt.Println("断点续传的坐标为", seekint)

		srcfile.Seek(int64(seekint), io.SeekStart)
		destfile.Seek(int64(seekint), io.SeekStart)
		sum = seekint

		for {
			currentreadlen, eioerr := srcfile.Read(bytes)

			if eioerr != nil || currentreadlen == 0 {
				fmt.Println("文件读取完毕")
				temptxt.Close()
				os.Remove(temp)
				return
			}
			destfile.Write(bytes)
			sum += int64(currentreadlen)
			temptxt.WriteString(strconv.Itoa(int(sum)))
			temptxt.Seek(0, io.SeekStart)

		}

	}

}
